import express, { Request, Response } from 'express';
import { sseManager } from '../sse/SseManager';
import {getStrategy} from "../brand/strategyFactory";
import {AppDataSource} from "../config/database";
import {Device} from "../entity/Device";
import { User } from '../entity/User';

const sseRouter = express.Router();


// 建立 SSE 连接
sseRouter.get('/events', async (req, res) => {
  try {

    const userId = req.query.sseconid as string;
    if (!userId) {
      res.status(400).json({code: 400, message: ' 缺失参数 sseconid '});
      return;
    }

    const repo = AppDataSource.getRepository(User);
    const existing = await repo.findOne({where: {userId}});
    if(!existing){
      res.status(403).json( {code:403, message: 'sseconid 无效'});
    }

    sseManager.register(userId, res);
  } catch (e: any) {
    res.status(500).json({code: 500, message: `服务器内部错误: ${e.message}`});
  }
});


// 客户端主动退出接口
sseRouter.post('/api/sse/exit', async (req: Request, res: Response) => {
  const userId = req.body.sseconid as string;
  if (!userId || typeof userId !== 'string') {
    res.status(400).json({message: '参数 sseconid 缺失或无效'});
    return;
  }

  // 如果没有连接，直接返回 404
  const closed = sseManager.close(userId);
  if (!closed) {
    res.status(404).json({message: '连接不存在或已关闭'});
    return;
  }

  // 获取当前用户的所有设备
  const repo = AppDataSource.getRepository(Device);
  const devices = await repo.find({where: {userId}});

  // 按品牌取消订阅
  const grouped = new Map<string, string[]>(); // brand -> did[]
  for (const dev of devices) {
    if (!grouped.has(dev.brand)) grouped.set(dev.brand, []);
    grouped.get(dev.brand)!.push(dev.did);
  }

  for (const [brand, dids] of grouped.entries()) {
    try {
      const strategy = getStrategy(brand);
      if (strategy.revokeDeviceSubscription) {
        for (const did of dids) {
          await strategy.revokeDeviceSubscription(userId, did);
        }
      }
    } catch (err) {
      console.warn(`[SSE EXIT] ${brand} 设备订阅取消失败:`, err);
    }
  }

  res.status(204).send(); // 成功但无内容
  return;
});





export default sseRouter;
